package com.jnu.myaccount;

import androidx.activity.result.ActivityResult;
import androidx.activity.result.ActivityResultCallback;
import androidx.activity.result.ActivityResultLauncher;
import androidx.activity.result.contract.ActivityResultContracts;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;
import androidx.drawerlayout.widget.DrawerLayout;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.view.ContextMenu;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.google.android.material.floatingactionbutton.FloatingActionButton;
import com.google.android.material.navigation.NavigationView;
import com.jnu.myaccount.data.DataBank;
import com.jnu.myaccount.data.Money;
import com.jnu.myaccount.ui.AccountActivity;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;

public class MainActivity extends AppCompatActivity{

    private List<Money> moneyList=new ArrayList<>();
    private MyRecyclerViewAdapter myRecyclerViewAdapter;
    private DataBank dataBank;
    private DrawerLayout drawerLayout;
    private NavigationView navigationView;
    private ImageView menu;
    private TextView sumView;
    private TextView incomeView;
    private TextView spendView;
    private double incomeSum;
    private double spendSum;
    private double sum;
    int itemPosition;

    private void initMoneyList(){
        dataBank=new DataBank(MainActivity.this);
        moneyList=dataBank.loadData();
    }

    //接收更改的或添加的账单信息
    ActivityResultLauncher<Intent> launcherRegister = registerForActivityResult(new ActivityResultContracts.StartActivityForResult(), new ActivityResultCallback<ActivityResult>(){
        @Override
        public void onActivityResult(ActivityResult result) {
            Intent data=result.getData();
            int resultCode = result.getResultCode();
            if(resultCode==1)
            {
                Money money=(Money) data.getSerializableExtra("money");
                int position=data.getIntExtra("position",0);
                if(money.isIncome()){
                    sum+=money.getMoney_number();
                    for(int i=0;i<moneyList.size();i++){
                        if(money.getMoney_date().get(Calendar.YEAR) == moneyList.get(i).getMoney_date().get(Calendar.YEAR)
                                && money.getMoney_date().get(Calendar.MONTH) == moneyList.get(i).getMoney_date().get(Calendar.MONTH)
                                && money.getMoney_date().get(Calendar.DAY_OF_MONTH) == moneyList.get(i).getMoney_date().get(Calendar.DAY_OF_MONTH)){
                            money.setIncome_sum(money.getIncome_sum()+moneyList.get(i).getIncome_sum());
                            break;
                        }
                    }
                    for(int i=0;i<moneyList.size();i++){
                        if(money.getMoney_date().get(Calendar.YEAR) == moneyList.get(i).getMoney_date().get(Calendar.YEAR)
                                && money.getMoney_date().get(Calendar.MONTH) == moneyList.get(i).getMoney_date().get(Calendar.MONTH)
                                && money.getMoney_date().get(Calendar.DAY_OF_MONTH) == moneyList.get(i).getMoney_date().get(Calendar.DAY_OF_MONTH)){
                            moneyList.get(i).setIncome_sum(money.getIncome_sum());
                        }
                    }
                }
                else {
                    sum-=money.getMoney_number();
                    for(int i=0;i<moneyList.size();i++){
                        if(money.getMoney_date().get(Calendar.YEAR) == moneyList.get(i).getMoney_date().get(Calendar.YEAR)
                                && money.getMoney_date().get(Calendar.MONTH) == moneyList.get(i).getMoney_date().get(Calendar.MONTH)
                                && money.getMoney_date().get(Calendar.DAY_OF_MONTH) == moneyList.get(i).getMoney_date().get(Calendar.DAY_OF_MONTH)){
                            money.setSpend_sum(money.getSpend_sum()+moneyList.get(i).getSpend_sum());
                            break;
                        }
                    }
                    for(int i=0;i<moneyList.size();i++){
                        if(money.getMoney_date().get(Calendar.YEAR) == moneyList.get(i).getMoney_date().get(Calendar.YEAR)
                                && money.getMoney_date().get(Calendar.MONTH) == moneyList.get(i).getMoney_date().get(Calendar.MONTH)
                                && money.getMoney_date().get(Calendar.DAY_OF_MONTH) == moneyList.get(i).getMoney_date().get(Calendar.DAY_OF_MONTH)){
                            moneyList.get(i).setSpend_sum(money.getSpend_sum());
                        }
                    }
                }
                if(position!=-1){
                    moneyList.remove(position);
                    //myRecyclerViewAdapter.notifyItemRemoved(position);
                }
                for(int i=0;i<moneyList.size();i++){
                    if(money.getMoney_date().get(Calendar.YEAR) == moneyList.get(i).getMoney_date().get(Calendar.YEAR)
                            && money.getMoney_date().get(Calendar.MONTH) == moneyList.get(i).getMoney_date().get(Calendar.MONTH)
                            && money.getMoney_date().get(Calendar.DAY_OF_MONTH) == moneyList.get(i).getMoney_date().get(Calendar.DAY_OF_MONTH)){
                        money.setIs_date(false);
                        itemPosition=i+1;
                        moneyList.add(i+1,money);
                        myRecyclerViewAdapter.notifyItemChanged(i);
                        myRecyclerViewAdapter.notifyItemInserted(i+1);
                        break;
                    }
                    else if(money.getMoney_date().after(moneyList.get(i).getMoney_date())==true){
                        itemPosition=i;
                        moneyList.add(i,money);
                        myRecyclerViewAdapter.notifyItemInserted(i);
                        break;
                    }
                    else {
                        if(i==(moneyList.size()-1)){
                            itemPosition=i+1;
                            moneyList.add(i+1,money);
                            myRecyclerViewAdapter.notifyItemInserted(i+1);
                            break;
                        }
                    }
                }
                //没有数据时添加第一条数据
                if(moneyList.size()==0){
                    itemPosition=0;
                    moneyList.add(money);
                    myRecyclerViewAdapter.notifyItemInserted(0);
                }
                //myRecyclerViewAdapter.notifyDataSetChanged();
                dataBank.saveData();
                Toast.makeText(MainActivity.this,"已完成",Toast.LENGTH_LONG).show();
            }
        }
    });

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        initMoneyList();
        RecyclerView recyclerView = (RecyclerView) findViewById(R.id.my_recyclerview);
        LinearLayoutManager layoutManager = new LinearLayoutManager(this);
        recyclerView.setLayoutManager(layoutManager);
        myRecyclerViewAdapter = new MainActivity.MyRecyclerViewAdapter(this, new OnItemClickCallback() {
            @Override
            public void onClick(View view, Money money) {
                Intent intent=new Intent(MainActivity.this,BillingDetails.class);
                intent.putExtra("moneyNumber",String.valueOf(money.getMoney_number()));
                intent.putExtra("moneyName",money.getMoney_name());
                String moneyStyle;
                if(money.isIncome()){
                    moneyStyle="收入";
                }
                else {
                    moneyStyle="支出";
                }
                intent.putExtra("moneyStyle",moneyStyle);
                String moneyDate;
                int year=money.getMoney_date().get(Calendar.YEAR);
                int month=money.getMoney_date().get(Calendar.MONTH)+1;
                int day=money.getMoney_date().get(Calendar.DAY_OF_MONTH);
                moneyDate=year+"-"+month+"-"+day;
                intent.putExtra("moneyDate",moneyDate);
                intent.putExtra("moneyImage",money.getMoney_id());
                startActivity(intent);
            }
        },moneyList);
        recyclerView.setAdapter(myRecyclerViewAdapter);
        registerForContextMenu(recyclerView);

        FloatingActionButton floatingActionButton=findViewById(R.id.floatingActionButton);
        floatingActionButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent intent=new Intent(MainActivity.this,AccountActivity.class);
                launcherRegister.launch(intent);
            }
        });

        sumView=findViewById(R.id.sum_view);
        incomeView =findViewById(R.id.income);
        spendView =findViewById(R.id.spend);
        incomeSum=0.0;
        spendSum=0.0;
        sum=0.0;
        itemPosition=-1;
        Calendar ThisMonth=Calendar.getInstance();
        for(int i=0;i<moneyList.size();i++){
            if(moneyList.get(i).isIncome()){
                if(ThisMonth.get(Calendar.YEAR) == moneyList.get(i).getMoney_date().get(Calendar.YEAR)
                        && ThisMonth.get(Calendar.MONTH) == moneyList.get(i).getMoney_date().get(Calendar.MONTH)){
                    incomeSum+=moneyList.get(i).getMoney_number();
                }
                sum+=moneyList.get(i).getMoney_number();
            }
            else {
                if(ThisMonth.get(Calendar.YEAR) == moneyList.get(i).getMoney_date().get(Calendar.YEAR)
                        && ThisMonth.get(Calendar.MONTH) == moneyList.get(i).getMoney_date().get(Calendar.MONTH)){
                    spendSum+=moneyList.get(i).getMoney_number();
                }
                sum-=moneyList.get(i).getMoney_number();
            }
        }

        drawerLayout = (DrawerLayout) findViewById(R.id.activity_na);
        navigationView = (NavigationView) findViewById(R.id.nav);
        menu= (ImageView) findViewById(R.id.main_menu);
        View headerView = navigationView.getHeaderView(0);//获取头布局
        drawerLayout.setFitsSystemWindows(true);
        drawerLayout.setClipToPadding(false);
        navigationView.inflateMenu(R.menu.student_menu);
        ImageView imageView=headerView.findViewById(R.id.person);
        imageView.setImageResource(R.drawable.student);
        menu.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (drawerLayout.isDrawerOpen(navigationView)){
                    drawerLayout.closeDrawer(navigationView);
                }else{
                    drawerLayout.openDrawer(navigationView);
                }

            }
        });
        navigationView.setNavigationItemSelectedListener(new NavigationView.OnNavigationItemSelectedListener() {
            @Override
            public boolean onNavigationItemSelected(@NonNull MenuItem item) {
                //item.setChecked(true);
                switch (item.getItemId()){
                    case R.id.style_manager:
                        Intent intent=new Intent(MainActivity.this,StyleManager.class);
                        startActivity(intent);
                        break;
                    case R.id.quit:
//                        intent=new Intent(MainActivity.this,LoginActivity.class);
//                        DataBank dataBank=new DataBank(MainActivity.this);
//                        dataBank.loadData();
//                        User user=dataBank.getUser();
//                        user.setAccount("account");
//                        dataBank.saveData();
//                        startActivity(intent);
//                        break;
                    case R.id.set:
//                        intent=new Intent(MainActivity.this,PointStore.class);
//                        intent.putExtra("Point",user_1.getPoint());
//                        intent.putExtra("Account",user_1.getAccount());
//                        startActivity(intent);
//                        break;
                    case R.id.personal_center:
//                        intent=new Intent(MainActivity.this,personal_center.class);
//                        startActivity(intent);
                }
                drawerLayout.closeDrawer(navigationView);
                return true;
            }
        });
    }

    private class MyRecyclerViewAdapter extends RecyclerView.Adapter implements OnItemClickCallback {
        private List<Money> moneyList;
        // item条目布局注入器
        private LayoutInflater mInflater;
        // 申明一个点击事件接口变量
        private OnItemClickCallback callback = null;

        public MyRecyclerViewAdapter(Context ctx, OnItemClickCallback clickCallback,List<Money> moneyList){
            this.mInflater = LayoutInflater.from(ctx);
            this.callback = clickCallback;
            this.moneyList=moneyList;
        }

        @NonNull
        @Override
        public RecyclerView.ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
            View view= LayoutInflater.from(parent.getContext()).inflate(R.layout.money_item,parent,false);
            MyViewHolder holder=new MyViewHolder(view);
            return holder;
        }
        @Override
        public void onBindViewHolder(@NonNull RecyclerView.ViewHolder Holder, @SuppressLint("RecyclerView") int position) {
            MainActivity.MyRecyclerViewAdapter.MyViewHolder holder=(MainActivity.MyRecyclerViewAdapter.MyViewHolder) Holder;

            // 给item中的指定控件添加点击事件（可以是item的子控件，也可以是itemView本身）
            holder.itemView.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    callback.onClick(view,moneyList.get(position));
                }
            });

            holder.getMoneyImage().setImageResource(moneyList.get(position).getMoney_id());
            holder.getMoneyText().setText(moneyList.get(position).getMoney_name());
            Calendar ThisMonth=Calendar.getInstance();
            if(itemPosition==position){
                if(moneyList.get(itemPosition).isIncome()){
                    if(ThisMonth.get(Calendar.YEAR) == moneyList.get(itemPosition).getMoney_date().get(Calendar.YEAR)
                            && ThisMonth.get(Calendar.MONTH) == moneyList.get(itemPosition).getMoney_date().get(Calendar.MONTH)){
                        incomeSum+=moneyList.get(itemPosition).getMoney_number();
                    }
                    sum+=moneyList.get(itemPosition).getMoney_number();
                }
                else {
                    if(ThisMonth.get(Calendar.YEAR) == moneyList.get(itemPosition).getMoney_date().get(Calendar.YEAR)
                            && ThisMonth.get(Calendar.MONTH) == moneyList.get(itemPosition).getMoney_date().get(Calendar.MONTH)){
                        spendSum+=moneyList.get(itemPosition).getMoney_number();
                    }
                    sum-=moneyList.get(itemPosition).getMoney_number();
                }
            }
            sumView.setText("净资产："+sum);
            incomeView.setText("本月收入："+incomeSum);
            spendView.setText("本月支出："+spendSum);
            int year=moneyList.get(position).getMoney_date().get(Calendar.YEAR);
            int month=moneyList.get(position).getMoney_date().get(Calendar.MONTH)+1;
            int date=moneyList.get(position).getMoney_date().get(Calendar.DAY_OF_MONTH);
            double incomeSum=moneyList.get(position).getIncome_sum();
            double spendSum=moneyList.get(position).getSpend_sum();
            if(moneyList.get(position).isIncome()){
                holder.getMoneyNumber().setText(String.valueOf(moneyList.get(position).getMoney_number()));
            }
            else {
                holder.getMoneyNumber().setText("-"+String.valueOf(moneyList.get(position).getMoney_number()));
            }
            if(moneyList.get(position).getIs_date()==true){
                holder.getMoneyDate().setText("日期："+year+"-"+month+"-"+date);
                holder.moneyStyle.setText("收入："+incomeSum+"  "+"支出："+spendSum);
            }
            else if(moneyList.get(position).getIs_date()==false){
                holder.linearLayout.setVisibility(View.GONE);
            }
        }

        @Override
        public int getItemCount() {
            return moneyList.size();
        }

        @Override
        public void onClick(View view, Money money) {

        }

        private class MyViewHolder extends RecyclerView.ViewHolder implements View.OnCreateContextMenuListener, MenuItem.OnMenuItemClickListener {

            public static final int CONTEXT_MENU_ID_ADD=1;
            public static final int CONTEXT_MENU_ID_EDIT = 2;
            public static final int CONTEXT_MENU_ID_DELETE = 3;
            int position;
            View moneyView;

            public ImageView getMoneyImage() {
                return moneyImage;
            }

            public TextView getMoneyText() {
                return moneyText;
            }

            public TextView getMoneyNumber() {
                return moneyNumber;
            }

            public void setMoneyDate(TextView moneyDate) {
                this.moneyDate = moneyDate;
            }

            public TextView getMoneyDate() {
                return moneyDate;
            }

            //日期、图片、支出或收入名称、数目、收入或支出
            TextView moneyDate;
            ImageView moneyImage;
            TextView moneyText;
            TextView moneyNumber;
            TextView moneyStyle;

            public LinearLayout getLinearLayout() {
                return linearLayout;
            }

            LinearLayout linearLayout;

            public MyViewHolder(@NonNull View itemView) {
                super(itemView);
                moneyView=itemView;
                moneyStyle=itemView.findViewById(R.id.money_style);
                moneyDate=itemView.findViewById(R.id.money_date);
                moneyImage=itemView.findViewById(R.id.money_image);
                moneyText=itemView.findViewById(R.id.money_text);
                moneyNumber=itemView.findViewById(R.id.money_number);
                linearLayout=itemView.findViewById(R.id.actionUp);
                itemView.setOnCreateContextMenuListener(this);
            }

            @Override
            public boolean onMenuItemClick(MenuItem menuItem) {
                //获取被点击的position
                itemPosition=getAdapterPosition();
                View dialogue_View=LayoutInflater.from(MainActivity.this).inflate(R.layout.fragment_acount,null);
                AlertDialog.Builder alertDialog_Builder=new AlertDialog.Builder(MainActivity.this);
                alertDialog_Builder.setView(dialogue_View);
                TextView nameView=dialogue_View.findViewById(R.id.cost_name);
                EditText editMoney=dialogue_View.findViewById(R.id.editMoney);
                TextView dateView=dialogue_View.findViewById(R.id.date);
                switch (menuItem.getItemId()){
                    case CONTEXT_MENU_ID_ADD:
                        Intent intentAdd=new Intent(MainActivity.this, AccountActivity.class);
                        intentAdd.putExtra("name","add");
                        launcherRegister.launch(intentAdd);
                        break;
                    case CONTEXT_MENU_ID_EDIT:
                        Intent intentEdit=new Intent(MainActivity.this,AccountActivity.class);
                        intentEdit.putExtra("name","edit");
                        nameView.setText(moneyList.get(itemPosition).getMoney_name());
                        String moneyNumber= String.valueOf(moneyList.get(itemPosition).getMoney_number());
                        editMoney.setHint(moneyNumber);
                        String dateText=moneyList.get(itemPosition).getMoney_date().get(Calendar.YEAR)+"-"+moneyList.get(itemPosition).getMoney_date().get(Calendar.MONTH)+"-"+moneyList.get(itemPosition).getMoney_date().get(Calendar.DAY_OF_MONTH);
                        dateView.setText(dateText);
                        intentEdit.putExtra("editPosition",itemPosition);
                        Bundle bundle=new Bundle();
                        bundle.putInt("position",itemPosition);
                        bundle.putString("editName",moneyList.get(itemPosition).getMoney_name());
                        bundle.putDouble("editNumber",moneyList.get(itemPosition).getMoney_number());
                        bundle.putInt("editId",moneyList.get(itemPosition).getMoney_id());
                        bundle.putInt("Year",moneyList.get(itemPosition).getMoney_date().get(Calendar.YEAR));
                        bundle.putInt("Month",moneyList.get(itemPosition).getMoney_date().get(Calendar.MONTH));
                        bundle.putInt("Day",moneyList.get(itemPosition).getMoney_date().get(Calendar.DAY_OF_MONTH));
                        intentEdit.putExtras(bundle);
                        launcherRegister.launch(intentEdit);
                        break;
                    case CONTEXT_MENU_ID_DELETE:
                        tipDialog();
                        break;
                }
                return false;
            }

            @Override
            public void onCreateContextMenu(ContextMenu contextMenu, View v, ContextMenu.ContextMenuInfo menuInfo) {
                MenuItem add=contextMenu.add(Menu.NONE,CONTEXT_MENU_ID_ADD,CONTEXT_MENU_ID_ADD,"Add");
                MenuItem edit=contextMenu.add(Menu.NONE,CONTEXT_MENU_ID_EDIT,CONTEXT_MENU_ID_EDIT,"Edit");
                MenuItem delete=contextMenu.add(Menu.NONE,CONTEXT_MENU_ID_DELETE,CONTEXT_MENU_ID_DELETE,"Delete"+getAdapterPosition());

                add.setOnMenuItemClickListener(this);
                edit.setOnMenuItemClickListener(this);
                delete.setOnMenuItemClickListener(this);
            }
            private void tipDialog() {
                AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
                builder.setTitle("提示：");
                builder.setMessage("是否删除数据？");
                builder.setIcon(R.mipmap.ic_launcher);
                builder.setCancelable(true);            //点击对话框以外的区域是否让对话框消失

                //设置确定按钮
                builder.setPositiveButton("确定", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        if(position<moneyList.size()-1){
                            if(moneyList.get(position).isIncome()){
                                sum-=moneyList.get(position).getMoney_number();
                                for(int i=0;i<moneyList.size();i++){
                                    if(i!=position){
                                        if(moneyList.get(position).getMoney_date().get(Calendar.YEAR) == moneyList.get(i).getMoney_date().get(Calendar.YEAR)
                                                && moneyList.get(position).getMoney_date().get(Calendar.MONTH) == moneyList.get(i).getMoney_date().get(Calendar.MONTH)
                                                && moneyList.get(position).getMoney_date().get(Calendar.DAY_OF_MONTH) == moneyList.get(i).getMoney_date().get(Calendar.DAY_OF_MONTH)){
                                            moneyList.get(i).setIncome_sum(moneyList.get(position).getIncome_sum()-moneyList.get(position).getMoney_number());
                                        }
                                    }
                                }
                            }
                            else {
                                sum+=moneyList.get(position).getMoney_number();
                                for(int i=0;i<moneyList.size();i++){
                                    if(i!=position){
                                        if(moneyList.get(position).getMoney_date().get(Calendar.YEAR) == moneyList.get(i).getMoney_date().get(Calendar.YEAR)
                                                && moneyList.get(position).getMoney_date().get(Calendar.MONTH) == moneyList.get(i).getMoney_date().get(Calendar.MONTH)
                                                && moneyList.get(position).getMoney_date().get(Calendar.DAY_OF_MONTH) == moneyList.get(i).getMoney_date().get(Calendar.DAY_OF_MONTH)){
                                            moneyList.get(i).setSpend_sum(moneyList.get(i).getSpend_sum()-moneyList.get(position).getMoney_number());
                                        }
                                    }
                                }
                            }
                            if(moneyList.get(position).getIs_date()==true&&moneyList.get(position+1).getIs_date()==false){
                                moneyList.get(position+1).setIs_date(true);
                                myRecyclerViewAdapter.notifyItemChanged(position+1);
                                moneyList.remove(position);
                                myRecyclerViewAdapter.notifyItemRemoved(position);
                                notifyItemRangeChanged(position, moneyList.size() - position);
                            }
                            else {
                                moneyList.remove(position);
                                myRecyclerViewAdapter.notifyItemRemoved(position);
                                notifyItemRangeChanged(position, moneyList.size() - position);
                            }
                        }
                        else{
                            moneyList.remove(position);
                            myRecyclerViewAdapter.notifyItemRemoved(position);
                            notifyItemRangeChanged(position, moneyList.size() - position);
                        }
                        dataBank.saveData();
                        Toast.makeText(MainActivity.this,"已删除",Toast.LENGTH_LONG).show();
                        dialog.dismiss();
                    }
                });
                //设置取消按钮
                builder.setNegativeButton("取消", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        Toast.makeText(MainActivity.this, "已取消", Toast.LENGTH_LONG).show();
                        dialog.dismiss();
                    }
                });
                AlertDialog dialog = builder.create();
                dialog.show();
            }
        }
    }

    public interface OnItemClickCallback<T> {
        // 点击事件
        void onClick(View view , Money money);
    }
}